package netty_5;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

class ServerHandler extends ChannelHandlerAdapter{
    /**
     * 当通道被调用，执行此方法
     * */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        String value = (String)msg;
        System.out.println("服务端收到客户端msg:" + msg);
        //回复客户端1
        ctx.writeAndFlush(Unpooled.copiedBuffer(value.getBytes()));
//        ctx.write("client msg:" + value);
//        ctx.flush();
    }
}

/**
 * 服务端
 * */
public class Netty_5_Server {

    public static void main(String[] args) throws InterruptedException {
        try{
            System.out.println("...服务器启动");
            //1.创建两个线程池，一个负责接收客户端，一个进行传输
            NioEventLoopGroup acceptGroup = new NioEventLoopGroup();
            NioEventLoopGroup sendGroup = new NioEventLoopGroup();
            //2.创建辅助类
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(acceptGroup,sendGroup).channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .option(ChannelOption.SO_SNDBUF,32*1024)
                    .option(ChannelOption.SO_RCVBUF,32*1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel socketChannel) throws Exception {
                            //每10个字符拆包
                        socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(10));
                            //以指定的字符拆包
//                        ByteBuf buf = Unpooled.copiedBuffer("_mayi".getBytes("GBK"));
//                        socketChannel.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));
                            socketChannel.pipeline().addLast(new StringDecoder());
                            socketChannel.pipeline().addLast(new ServerHandler());
                        }
                    });
            //启动
            ChannelFuture cf = serverBootstrap.bind(8087).sync();
            //关闭
            cf.channel().closeFuture().sync();
            acceptGroup.shutdownGracefully();
            sendGroup.shutdownGracefully();
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
